import React from 'react';
import moment from 'moment';
import api from 'js/api/index';
import { List, Toast } from 'antd-mobile';
import InfiniteScroll from 'react-infinite-scroller';
import { SelectDate, SelectDateComponent } from 'views/component/selectDate/selectDate';
import SelectTitle from 'views/component/selectTitle/selectTitle';
import { SubViewLink } from 'views/component/subViewLink/subViewLink';
import { hashHistory } from 'react-router';
import TableBox from 'views/component/table/table';
import { i18n } from 'js/core/i18n';
import './monitoring.scss';

let pagesize = 10;

class Main extends React.Component {
  constructor() {
    super()
    this.query = {
      ShopId: '',
    }
    this.state = {
      shop: null,
      data: [],
      list: [],
      videoUrl: null,
      videoHidden: false,
      devid: null
    }
  }
  componentDidMount = () => {
    this.ShopList();
  }
  ShopList = () => {
    api('/BaseSet/ShopList').then(data => {
      this.query.ShopId = data.data[0].ShopId;
      this.setState({ shop: data.data[0] })
      this.getData();
    });
  }
  shopNameOnChange = (shopInfo) => {
    this.query.ShopId = shopInfo.ShopId;
    this.setState({ shop: shopInfo })
    this.getData();
  }
  getData = () => {
    api('/Device/GiveUDeviceInfo', this.query).then((data) => {
      if (data.result && data.result.length > 0) {
        let list = data.result.map(item => {
          return {
            SNo: item.SNo,
            ShopId: item.ShopId,
            iChNo: item.iChNo,
          }
        });
        list = [
          { SNo: "e528c2b5944f502c", ShopId: 2, iChNo: 0 }
        ];
        this.setState({ data: data.result, list: list, videoUrl: data.result[0].videoUrl, devid: data.result[0].devid }, () => {
          this.openVideo(data.result[0].videoUrl);
        })
      } else {
        this.setState({ data: [], list: [], videoUrl: null, devid: null })
      }
    });
  }
  dateOnChange = (value) => {
    this.query.start = value[0];
    this.query.end = value[1];
    this.setState({ start: value[0], end: value[1], data: [], hasMore: true })
  }
  look = (data, item) => {
    // data = [{ "SHOPID": "1030210001", "SHOPNAME": "Shanghai 02 Mall", "MEDIATYPENAME": "ç›‘æŽ§", "SERVER": "app.umeye.cn", "PORT": "8300", "DEVID": "xmks9iph289u", "USERNAME": "admin", "PASSWORD": "pagoda2016", "DEVNAME": "test5", "DEVCH": "0", "PLAYTYPE": "1", "ORDER": "5" },
    // { "SHOPID": "1030210001", "SHOPNAME": "Shanghai 02 Mall", "MEDIATYPENAME": "å®¢æµ", "SERVER": "app.umeye.cn", "PORT": "8300", "DEVID": "xmkst9ryrhhx", "USERNAME": "admin", "PASSWORD": "pagoda-cd", "DEVNAME": "test3", "DEVCH": "1", "PLAYTYPE": "1", "ORDER": "2" },
    // {
    //   "SHOPID": "1030210001", "SHOPNAME": "Shanghai 02 Mall", "MEDIATYPENAME": "å®¢æµ", "SERVER": "app.umeye.cn", "PORT": "8300",
    //   "DEVID": "xmks9iph289u", "USERNAME": "admin", "PASSWORD": "pagoda2016", "DEVNAME": "test4", "DEVCH": "1", "PLAYTYPE": "1", "ORDER": "4"
    // }]

    // data = [{ "SHOPID": "1030210001", "SHOPNAME": "Shanghai 02 Mall", "MEDIATYPENAME": "ç›‘æŽ§", "SERVER": "app.umeye.cn", "PORT": "8300", "DEVID": "xmks9iph289u", "USERNAME": "admin", "PASSWORD": "pagoda2016", "DEVNAME": "test5", "DEVCH": "0", "PLAYTYPE": "1", "ORDER": "5" }];
    // let d = [];
    // d = [{
    //   SHOPID: item.ShopId + '', SHOPNAME: item.ShopName, SERVER: 'app.umeye.cn', PORT: '8300', USERNAME: 'admin', PASSWORD: '', DEVID: item.devid, DEVNAME: '实时视频', DEVCH: item.iChNo + "", PLAYTYPE: 1 + "", ORDER: 0 + ""
    // }];
    // var isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    // if (isiOS) {
    //   Cordova.exec(function (winParam) { }, function (error) { }, "VideoPlugin", "show", data);
    // } else {
    //   window.fwJs.test(JSON.stringify({
    //     result: data
    //   }));
    // }

    this.setState({ videoUrl: item.videoUrl, devid: item.devid }, () => {
      this.openVideo(item.videoUrl)
    })
  }
  componentWillUnmount = () => {
    if (this.player) {
      this.player.remove();
      this.player = null;
    }
  }
  openVideo = (url) => {
    if (url === "" || !url) {
      this.setState({ videoUrl: null })
      return
    }

    // if (this.player) {
    //   this.player.remove();
    //   this.player = null;
    // }
    // this.player = cyberplayer('video').setup({
    //   title: "",
    //   file: url,
    //   width: "100%",
    //   height: "4.8rem",
    //   autostart: false, // 是否自动播放
    //   stretching: "uniform", // 拉伸设置
    //   repeat: false, // 是否重复播放
    //   volume: 100, // 音量
    //   controls: true, // controlbar是否显示
    //   starttime: 0, // 视频开始播放时间点(单位s)，如果不设置，则可以从上次播放时间点续播
    //   ak: "c68bed734ce6488d82e0cfb37fd85d31"
    // });

    var video = document.getElementById('video');
    if (Hls.isSupported()) {
      var hls = new Hls();
      hls.loadSource(url);
      hls.attachMedia(video);
      hls.on(Hls.Events.MANIFEST_PARSED, function () {
        video.play();
      });
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = url;
      video.addEventListener('canplay', function () {
        video.play();
      });
    }
  }
  MonitoringCapture = () => {
    api('/Monitoring/MonitoringCapture', {
      ShopId: this.state.shop.ShopId,
      list: this.state.list,
    }, 'POST').then((data) => {
      Toast.success(i18n.get('新建成功'), 2);
      if (this.props.complete) {
        this.props.complete();
        FW.emit('back');
      }
    })
  }
  complete = () => {
    if (this.props.complete) {
      this.props.complete();
      setTimeout(() => {
        FW.emit('back');
      }, 550)
    }
  }
  closeCb = () => {
    console.log('closeCb')
    this.setState({ videoHidden: false })
  }
  subViewOnClickCb = () => {
    console.log('subViewOnClickCb')
    this.setState({ videoHidden: true })
  }
  render() {
    let { data, shop, list, videoUrl, devid, videoHidden } = this.state;
    return <div id="monitoring" className="flex-col">
      <div className="device-container">
        <List className="picker-list mb20">
          <div className="deviceItem device-border flex-vcenter">
            <SelectTitle classStyle="name">{i18n.get('选择店铺')}</SelectTitle>
            <SubViewLink moduleName="shopSearch" className="flex-g-1 text-right deviceItemContent" title={i18n.get('选择店铺')} modelData={{ onChange: this.shopNameOnChange }}
              closeCb={this.closeCb} subViewOnClickCb={this.subViewOnClickCb}
            >
              {shop ? shop.ShopName : <div style={{ color: '#909090' }}>{i18n.get('选择店铺')}</div>}
            </SubViewLink>
          </div>
        </List>
      </div>
      <div className="video flex-center">
        {/* {videoUrl?<video src={videoUrl} controls autobuffer preload autoplay="autoplay" key={devid}></video>:<div>{i18n.get('暂无监控视频')}</div>} */}
        <div className={(videoUrl && videoHidden == false) ? "videoUrl " : "videoUrl hidden"}>
          <video className={(videoHidden == false) ? "" : " hidden"} id={"video"}></video>
        </div>
        {!videoUrl && <div>{i18n.get('暂无监控视频')}</div>}
        {/* <video src={require("./video.mp4")} poster="" controls autobuffer preload autoplay></video> */}
      </div>
      <div className="flex-g-1 scroll-absolute">
        <div>
          <TableBox heads={[i18n.get('门店名称'), i18n.get('设备状态'), i18n.get('位置'), i18n.get('操作')]} >
            {data.map((item, index) => (
              <tr className={item.devid === devid ? "active" : ""} key={item.devid}>
                <td>{item.ShopName}</td>
                <td>{item.DeviceStatus}</td>
                <td>{item.DevicePosition}</td>
                <td onClick={() => { this.look(data, item) }}>{i18n.get("查看实时视频")}</td>
              </tr>
            ))}
          </TableBox>
          {data.length === 0 && <div className="flex-center no-data">{i18n.get('暂无数据')}</div>}
        </div>
      </div>
      <div>
        {list.length > 0 &&
          <SubViewLink className="device-btn" moduleName="monitoringMatch" title={i18n.get("评分")} modelData={{ id: shop ? shop.ShopId : 0, list: list }}
            closeCb={this.closeCb} subViewOnClickCb={this.subViewOnClickCb}
          >
            <button type="button" className="btn btn-primary">{i18n.get("评分")}</button>
          </SubViewLink>}
      </div>
    </div>
  }
}

export default Main;